<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author ThinkGem
-->
<template>
  <div>
    <!-- 选项卡 -->
    <div style="margin-bottom: 10px; border-bottom: 1px solid #e8e8e8">
      <div style="display: flex; background: #fafafa">
        <div
          @click="handleTabChange('exception')"
          :style="{
            padding: '12px 24px',
            cursor: 'pointer',
            borderBottom:
              currentTab === 'exception' ? '2px solid #1890ff' : '2px solid transparent',
            color: currentTab === 'exception' ? '#1890ff' : '#666',
            fontWeight: currentTab === 'exception' ? 'bold' : 'normal',
            background: currentTab === 'exception' ? '#fff' : 'transparent',
            marginBottom: '-1px',
          }"
        >
          异常信息处理
        </div>
        <div
          @click="handleTabChange('duplicate')"
          :style="{
            padding: '12px 24px',
            cursor: 'pointer',
            borderBottom:
              currentTab === 'duplicate' ? '2px solid #1890ff' : '2px solid transparent',
            color: currentTab === 'duplicate' ? '#1890ff' : '#666',
            fontWeight: currentTab === 'duplicate' ? 'bold' : 'normal',
            background: currentTab === 'duplicate' ? '#fff' : 'transparent',
            marginBottom: '-1px',
          }"
        >
          重复账号确认
        </div>
      </div>
    </div>

    <!-- 表格内容 -->
    <BasicTable @register="registerTable">
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="pr-1 m-1" />
        <span> {{ getTitle.value }} </span>
      </template>

      <template #firstColumn="{ record }">
        <span :title="currentTab === 'duplicate' ? record.name1 : record.vstudent?.studentNumber">
          {{ currentTab === 'duplicate' ? record.name1 : record.vstudent?.studentNumber }}
        </span>
      </template>

      <!-- 重复账号确认的插槽 -->
      <template #vGrade1="{ column, record }">
        <DictLabel :dictType="column.dictType" :dictValue="record.grade1" />
      </template>
      <template #vClass1="{ column, record }">
        <DictLabel :dictType="column.dictType" :dictValue="record.class1" />
      </template>
      <template #vSex1="{ column, record }">
        <DictLabel
          v-if="record.sex1 && record.sex1 !== '-'"
          :dictType="column.dictType"
          :dictValue="record.sex1"
        />
        <span v-else>-</span>
      </template>
      <template #vGrade2="{ column, record }">
        <DictLabel :dictType="column.dictType" :dictValue="record.grade2" />
      </template>
      <template #vClass2="{ column, record }">
        <DictLabel :dictType="column.dictType" :dictValue="record.class2" />
      </template>
      <template #vSex2="{ column, record }">
        <DictLabel
          v-if="record.sex2 && record.sex2 !== '-'"
          :dictType="column.dictType"
          :dictValue="record.sex2"
        />
        <span v-else>-</span>
      </template>

      <!-- 异常信息处理的插槽 -->
      <template #vStudentStatus="{ column, record }">
        <DictLabel
          v-if="record.vstudent"
          :dictType="column.dictType"
          :dictValue="record.vstudent.studentStatus"
        />
      </template>
      <template #vSex="{ column, record }">
        <DictLabel
          v-if="record.vstudent"
          :dictType="column.dictType"
          :dictValue="record.vstudent.sex"
        />
      </template>
      <template #vGrade="{ column, record }">
        <DictLabel
          v-if="record.vstudent"
          :dictType="column.dictType"
          :dictValue="record.vstudent.grade"
        />
      </template>
      <template #vClass="{ column, record }">
        <DictLabel
          v-if="record.vstudent"
          :dictType="column.dictType"
          :dictValue="record.vstudent.classCode"
        />
      </template>
    </BasicTable>
    <InputForm
      @register="registerDrawer"
      @success="handleSuccess"
      @ignore="handleIgnoreFromForm"
      @process="handleProcessFromForm"
    />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsVkeExceptionInfoList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, watch, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { DictLabel } from '/@/components/Dict';
  import { FormProps } from '/@/components/Form';
  import { useDrawer } from '/@/components/Drawer';

  import {
    vstudentUpdateRecordListData,
    vstudentMergeRecordListData,
    vstudentUpdateRecordUpdate,
    vuserDisableNoPer,
  } from '/@/api/vke/exceptionInfo';
  import InputForm from './form.vue';

  const props = defineProps({
    treeCode: String,
    tabType: {
      type: String,
      default: 'exception',
    },
  });

  const { t } = useI18n('vke.exceptionInfo');
  const { showMessage } = useMessage();

  // 选项卡状态 - 默认显示异常信息处理
  const currentTab = ref<string>('exception');

  const getTitle = computed(() => ({
    icon: 'simple-line-icons:exclamation',
    value: currentTab.value === 'duplicate' ? t('重复账号确认') : t('异常信息处理'),
  }));

  const param = ref({});
  // 根据选项卡类型返回不同的搜索表单配置
  const searchForm = computed<FormProps>(() => {
    if (currentTab.value === 'duplicate') {
      // 重复账号确认的搜索表单
      return {
        baseColProps: { lg: 4, md: 4 },
        labelWidth: 100,
        schemas: [
          {
            label: t('学生姓名'),
            field: 'studentName',
            component: 'Input',
          },
          {
            label: t('年级'),
            field: 'grade',
            component: 'Select',
            componentProps: {
              dictType: 'vke_grade',
              allowClear: true,
              onChange: handleSuccess,
            },
          },
          {
            label: t('班级'),
            field: 'classCode',
            component: 'Select',
            componentProps: {
              dictType: 'vke_class',
              allowClear: true,
              onChange: handleSuccess,
            },
          },
        ],
      };
    } else {
      // 异常信息处理的搜索表单
      return {
        baseColProps: { lg: 4, md: 4 },
        labelWidth: 100,
        schemas: [
          {
            label: t('学号'),
            field: 'vstudent.studentNumber',
            component: 'Input',
          },
          {
            label: t('姓名'),
            field: 'vstudent.studentName',
            component: 'Input',
          },
          {
            label: t('性别'),
            field: 'vstudent.sex',
            component: 'Select',
            componentProps: {
              dictType: 'sys_user_sex',
              allowClear: true,
            },
          },
          {
            label: t('身份证号'),
            field: 'vstudent.identityCard',
            component: 'Input',
          },
          {
            label: t('年级'),
            field: 'vstudent.grade',
            component: 'Select',
            componentProps: {
              dictType: 'vke_grade',
              allowClear: true,
              onChange: handleSuccess,
            },
          },
          {
            label: t('班级'),
            field: 'vstudent.classCode',
            component: 'Select',
            componentProps: {
              dictType: 'vke_class',
              allowClear: true,
              onChange: handleSuccess,
            },
          },
          {
            label: t('上报原因'),
            field: 'remarks',
            component: 'Input',
          },
          {
            label: t('学籍状态'),
            field: 'vstudent.studentStatus',
            component: 'Select',
            componentProps: {
              dictType: 'vke_student_status',
              allowClear: true,
            },
          },
        ],
      };
    }
  });

  // 根据选项卡类型返回不同的表格列配置
  const tableColumns = computed<BasicColumn[]>(() => {
    if (currentTab.value === 'duplicate') {
      // 重复账号确认的列配置
      return [
        {
          title: t('学生1姓名'),
          dataIndex: 'name1',
          key: 'name1',
          sorter: true,
          width: 120,
          slots: { customRender: 'firstColumn' },
        },
        {
          title: t('学生1ID'),
          dataIndex: 'id1',
          key: 'id1',
          sorter: true,
          width: 150,
        },
        {
          title: t('学生1年级'),
          dataIndex: 'grade1',
          key: 'grade1',
          sorter: true,
          width: 80,
          dictType: 'vke_grade',
          slots: { customRender: 'vGrade1' },
        },
        {
          title: t('学生1班级'),
          dataIndex: 'class1',
          key: 'class1',
          sorter: true,
          width: 80,
          dictType: 'vke_class',
          slots: { customRender: 'vClass1' },
        },
        {
          title: t('学生1性别'),
          dataIndex: 'sex1',
          key: 'sex1',
          sorter: true,
          width: 80,
          dictType: 'sys_user_sex',
          slots: { customRender: 'vSex1' },
        },
        {
          title: t('学生1身份证'),
          dataIndex: 'identityCard1',
          key: 'identityCard1',
          sorter: true,
          width: 180,
        },
        {
          title: t('学生2姓名'),
          dataIndex: 'name2',
          key: 'name2',
          sorter: true,
          width: 120,
        },
        {
          title: t('学生2ID'),
          dataIndex: 'id2',
          key: 'id2',
          sorter: true,
          width: 150,
        },
        {
          title: t('学生2年级'),
          dataIndex: 'grade2',
          key: 'grade2',
          sorter: true,
          width: 80,
          dictType: 'vke_grade',
          slots: { customRender: 'vGrade2' },
        },
        {
          title: t('学生2班级'),
          dataIndex: 'class2',
          key: 'class2',
          sorter: true,
          width: 80,
          dictType: 'vke_class',
          slots: { customRender: 'vClass2' },
        },
        {
          title: t('学生2性别'),
          dataIndex: 'sex2',
          key: 'sex2',
          sorter: true,
          width: 80,
          dictType: 'sys_user_sex',
          slots: { customRender: 'vSex2' },
        },
        {
          title: t('学生2身份证'),
          dataIndex: 'identityCard2',
          key: 'identityCard2',
          sorter: true,
          width: 180,
        },
      ];
    } else {
      // 异常信息处理的列配置
      return [
        {
          title: t('学号'),
          dataIndex: 'vstudent.studentNumber',
          key: 'vstudent.studentNumber',
          sorter: true,
          width: 100,
          slots: { customRender: 'firstColumn' },
        },
        {
          title: t('学生姓名'),
          dataIndex: 'vstudent.studentName',
          key: 'vstudent.studentName',
          sorter: true,
          width: 100,
        },
        {
          title: t('学籍状态'),
          dataIndex: 'vstudent.studentStatus',
          key: 'vstudent.studentStatus',
          sorter: true,
          width: 80,
          dictType: 'vke_student_status',
          slots: { customRender: 'vStudentStatus' },
        },
        {
          title: t('性别'),
          dataIndex: 'vstudent.sex',
          key: 'vstudent.sex',
          sorter: true,
          width: 80,
          dictType: 'sys_user_sex',
          slots: { customRender: 'vSex' },
        },
        {
          title: t('出生年月'),
          dataIndex: 'vstudent.dateBirth',
          key: 'vstudent.dateBirth',
          sorter: true,
          width: 100,
        },
        {
          title: t('身份证号'),
          dataIndex: 'vstudent.identityCard',
          key: 'vstudent.identityCard',
          sorter: true,
          width: 180,
        },
        {
          title: t('年级'),
          dataIndex: 'vstudent.grade',
          key: 'vstudent.grade',
          sorter: true,
          width: 80,
          dictType: 'vke_grade',
          slots: { customRender: 'vGrade' },
        },
        {
          title: t('班级'),
          dataIndex: 'vstudent.classCode',
          key: 'vstudent.classCode',
          sorter: true,
          width: 80,
          dictType: 'vke_class',
          slots: { customRender: 'vClass' },
        },
        {
          title: t('上报原因'),
          dataIndex: 'remarks',
          key: 'remarks',
          sorter: true,
          width: 280,
          ellipsis: true,
          customHeaderCell: () => ({
            style: {
              backgroundColor: '#fff2e8',
              fontWeight: 'bold',
              color: '#fa8c16',
            },
          }),
          customCell: () => ({
            style: {
              backgroundColor: '#fff7e6',
              fontWeight: '500',
              color: '#d46b08',
            },
          }),
        },
        {
          title: t('创建时间'),
          dataIndex: 'createDate',
          key: 'createDate',
          sorter: true,
          width: 130,
        },
      ];
    }
  });

  const actionColumn: BasicColumn = {
    width: 100,
    actions: (record: Recordable) => {
      // 重复账号确认选项卡的操作按钮
      if (currentTab.value === 'duplicate') {
        return [
          {
            icon: 'ant-design:check-outlined',
            color: 'success',
            title: t('确认合并'),
            popConfirm: {
              title: t('是否确认合并此重复账号'),
              confirm: handleMerge.bind(null, record),
            },
            // 重复账号确认数据没有status字段，所以总是显示按钮
          },
        ];
      }

      // 异常信息处理选项卡的操作按钮
      return [
        {
          icon: 'clarity:note-edit-line',
          title: t('编辑'),
          onClick: () => {
            // 传递完整的record数据和studentId
            handleForm({
              userCode: record.vstudent?.studentId,
              op: 'edit',
              exceptionRecord: record, // 传递异常信息记录
            });
          },
          // auth: 'vke:exceptionInfo:edit', // 暂时注释权限控制
        },
      ];
    },
  };

  // 动态API调用函数
  const dynamicApiCall = async (params: any) => {
    const apiFunction =
      currentTab.value === 'duplicate' ? vstudentMergeRecordListData : vstudentUpdateRecordListData;
    return await apiFunction(params);
  };

  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, getForm }] = useTable({
    api: dynamicApiCall,
    beforeFetch: (params) => {
      console.log(params);
      params.tabType = currentTab.value;
      param.value = params;
      return params;
    },
    immediate: false,
    columns: tableColumns,
    actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    rowKey: (record) =>
      currentTab.value === 'duplicate' ? `${record.id1}_${record.id2}` : record.id, // 设置唯一主键
  });

  onMounted(async () => {
    reload();
  });

  watch(
    () => props.treeCode,
    async () => {
      await getForm().setFieldsValue({
        'employee.office.officeCode': props.treeCode,
      });
      reload();
    },
  );

  watch(
    () => props.tabType,
    async (newTabType) => {
      if (newTabType && newTabType !== currentTab.value) {
        currentTab.value = newTabType;
      }
      reload();
    },
    { immediate: true },
  );

  async function handleProcess(id: string) {
    const params = {
      id: id,
      status: '1', // 已处理
    };
    const res = await vstudentUpdateRecordUpdate(params);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleMerge(record: Recordable) {
    const params = {
      id1: record.id1,
      id2: record.id2,
      grade: record.grade1, // 年级随便传一个
      classCode: record.class1, // 班级随便传一个
    };
    const res = await vuserDisableNoPer(params);
    showMessage(res.message);
    handleSuccess();
  }

  async function handleIgnore(id: string) {
    console.log('handleIgnore 被调用，ID:', id);

    if (!id) {
      showMessage('无法获取记录ID，忽略操作失败');
      return;
    }

    try {
      // 只用于异常信息处理的忽略操作
      const params = {
        id: id,
        status: '2', // 忽略
      };
      console.log('忽略操作参数:', params);

      const res = await vstudentUpdateRecordUpdate(params);
      console.log('忽略操作结果:', res);

      showMessage(res.message || '忽略操作成功');
      handleSuccess();
    } catch (error) {
      console.error('忽略操作失败:', error);
      showMessage('忽略操作失败');
    }
  }

  function handleSuccess() {
    reload();
  }

  // 选项卡切换函数
  function handleTabChange(tab: string) {
    currentTab.value = tab;
    reload(); // 重新加载数据
  }

  // 编辑功能
  function handleForm(record: Recordable) {
    openDrawer(true, record);
  }

  // 从表单触发的忽略操作
  async function handleIgnoreFromForm(id: string) {
    await handleIgnore(id);
  }

  // 从表单触发的已处理操作
  async function handleProcessFromForm(id: string) {
    await handleProcess(id);
  }
</script>
